package com.ruoyi.system.controller;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.TypeReference;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.mapper.ClassesMapper;
import com.ruoyi.system.mapper.GradesMapper;
import com.ruoyi.system.service.ICourseService;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.compress.utils.Lists;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * 课程表Controller
 * 课程表上传、解析、下载
 *
 * @author ruoyi
 * @date 2024-03-22
 */
@RestController
@RequestMapping("/system/course")
public class CourseController extends BaseController {

    @Autowired
    private ICourseService courseService;

    @Resource
    private GradesMapper gradesMapper;

    @Resource
    private ClassesMapper classesMapper;

    /**
     * 上传课程表并解析
     *
     * @return
     */
    @PreAuthorize("@ss.hasPermi('system:course:upload')")
    @ApiOperation("上传课程表并解析")
    @PostMapping("/upload")
    public AjaxResult upload(MultipartFile file, int isCover) throws IOException {
        int uploadAndSaveCourse = courseService.uploadAndSaveCourse(file, isCover);
        if (uploadAndSaveCourse == 2) {
            return AjaxResult.error("未从表格中读取年级、班级或格式错误");
        }
        if (uploadAndSaveCourse == 3) {
            return AjaxResult.error("当前表格中有系统中已存在的课程信息,是否需要覆盖");
        }
        if (uploadAndSaveCourse == 4) {
            return AjaxResult.error("上传文件失败,请检查格式,文件需为.xlsx类型");
        }
        if (uploadAndSaveCourse == 5) {
            return AjaxResult.error("表格中年度、学习、年级、班级都不能为空,请检查");
        }
        return toAjax(1);
    }

    /**
     * 导出课程解析列表
     */
    @PreAuthorize("@ss.hasPermi('system:course:export')")
    @Log(title = "课程解析", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public void export(HttpServletResponse response, Course course) {
        List<Course> courses = courseService.selectCourseList(course);

        List<CourseExcelData> list = Lists.newArrayList();
        CoursePlan plan = new CoursePlan();
        if (!CollectionUtils.isEmpty(courses)) {
            Course cs = courses.get(0);
            plan.setYear(cs.getYear_time());
            plan.setQuarter(cs.getSemester());
            Grades grades = gradesMapper.selectGradesByGid(cs.getGid());
            plan.setGrade(grades == null ? "" : grades.getGradeName());
            Classes clazz = classesMapper.selectClassesByCid(cs.getCid());
            plan.setClazz(clazz == null ? "" : clazz.getClassName());
            plan.setPeriod(JSON.parseObject(cs.getTime_period(), new TypeReference<List<String>>() {
            }));
            plan.setId(JSON.parseObject(cs.getClass_num(), new TypeReference<List<String>>() {
            }));
            plan.setMonday(JSON.parseObject(cs.getMonday(), new TypeReference<List<String>>() {
            }));
            plan.setTuesday(JSON.parseObject(cs.getTuesday(), new TypeReference<List<String>>() {
            }));
            plan.setWednesday(JSON.parseObject(cs.getWednesday(), new TypeReference<List<String>>() {
            }));
            plan.setThursday(JSON.parseObject(cs.getThursday(), new TypeReference<List<String>>() {
            }));
            plan.setFriday(JSON.parseObject(cs.getFriday(), new TypeReference<List<String>>() {
            }));
            plan.setSaturday(JSON.parseObject(cs.getSaturday(), new TypeReference<List<String>>() {
            }));
            plan.setSunday(JSON.parseObject(cs.getSunday(), new TypeReference<List<String>>() {
            }));
            for (int i = 0; i < plan.getPeriod().size(); i++) {
                CourseExcelData c = getCourseExcelData(plan, i);
                list.add(c);
            }
        }
        ExcelUtil<CourseExcelData> util = new ExcelUtil<>(CourseExcelData.class);
        util.exportExcel(response, list, "课程表数据", plan.getYear() + "学年度第" + plan.getQuarter() + "学期 " + plan.getGrade() + " " + plan.getClazz() + "课程表");
    }

    private static CourseExcelData getCourseExcelData(CoursePlan plan, int i) {
        CourseExcelData c = new CourseExcelData();
        c.setPeriod(plan.getPeriod().get(i));
        c.setId(plan.getId().get(i));
        c.setMonday(plan.getMonday().get(i));
        c.setTuesday(plan.getTuesday().get(i));
        c.setWednesday(plan.getWednesday().get(i));
        c.setThursday(plan.getThursday().get(i));
        c.setFriday(plan.getFriday().get(i));
        c.setSaturday(plan.getSaturday().get(i));
        c.setSunday(plan.getSunday().get(i));
        return c;
    }


    /**
     * 查询课程解析列表
     */
    @PreAuthorize("@ss.hasPermi('system:course:list')")
    @GetMapping("/list")
    public TableDataInfo list(Course course) {
        startPage();
        List<Course> courses = courseService.selectCourseList(course);
        return getDataTable(courses);
    }

    /**
     * 修改班级
     */
    @PreAuthorize("@ss.hasPermi('system:course:edit')")
    @Log(title = "课程", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody Course course) {
        return toAjax(courseService.updateCourse(course));
    }

    /**
     * 删除班级
     */
    @PreAuthorize("@ss.hasPermi('system:course:remove')")
    @Log(title = "课程", businessType = BusinessType.DELETE)
    @DeleteMapping("/{coids}")
    public AjaxResult remove(@PathVariable Long[] coids) {
        return toAjax(courseService.deleteCourseByCoids(coids));
    }

    /**
     * 获取课程解析详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:course:query')")
    @GetMapping(value = "/{coid}")
    public AjaxResult getInfo(@PathVariable("coid") Long coid)
    {
        return success(courseService.selectCourseByCoid(coid));
    }

}
